from django.shortcuts import render, redirect
from django.views import View
from userprofile.models import UserInfo, BusinessType
from django.contrib.auth import logout
from django.http import JsonResponse
from userprofile.forms import *
from business.models import Goods, Comments
from django.db.models import Q
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


# Create your views here.
def homePage(request):
    businesstype = BusinessType.objects.all()
    businesstype = list(businesstype.values('category', 'id'))
    print(list(businesstype))
    for bt in businesstype:
        btGlist = Goods.objects.filter(uploadUser__businessType=bt['id']).order_by('-lastChangeTime')
        btGlist = btGlist.values('id', 'goodsTitle', 'goodsPrice', 'goodsSrc', 'description')[:4]
        bt['data'] = btGlist
    print(businesstype)
    return render(request, 'home.html', locals())


class changePassword(View):
    def get(self, request):
        try:
            userInfo = UserInfo.objects.get(id=request.user.id)
            return render(request, 'userchangepassword.html', locals())
        except:
            return redirect('home:home_page')

    def post(self, request):
        data = {'isSuccess': 0}
        current_user = UserInfo.objects.get(id=request.user.id)
        # print(current_user.check_password(request.POST['OldPwd']))
        if current_user.check_password(request.POST['OldPwd']):
            data['isSuccess'] = 1
            current_user.set_password(request.POST['NewPwd'])
            current_user.save()
            logout(request)
        else:
            data['isSuccess'] = 0
        return JsonResponse(data)


class user_info(View):
    def get(self, request):
        try:
            userInfo = UserInfo.objects.get(id=request.user.id)
            return render(request, 'UserInfo.html', locals())
        except:
            return redirect('home:home_page')

    def post(self, request):
        data = {'msg': None}
        userid = request.POST.get('id')
        if userid:
            current_user = UserInfo.objects.get(id=userid)
            user_change_form = UserChangeForm(request.POST, instance=current_user)
            if user_change_form.is_valid():
                user_change_form.save()
                data['msg'] = '修改成功'
                return JsonResponse(data)
            else:
                data['msg'] = '修改失败'
                return JsonResponse(data)


def userChangeImg(request):
    if request.method == 'POST':
        data = {'msg': None}
        userid = request.POST.get('id')
        print(userid)
        if userid:
            current_user = UserInfo.objects.get(id=userid)
            user_change_form = UserChangeImgForm(request.POST, request.FILES, instance=current_user)
            print(user_change_form.errors)
            if user_change_form.is_valid():
                user_change_form.save()
                data['msg'] = '修改成功'
                return JsonResponse(data)
            else:
                data['msg'] = '修改失败'
                return JsonResponse(data)


def goodsList(request):
    key = request.GET.get('goodstype')
    print(key)
    currentType = '所有服务'
    if key:
        goodslists = Goods.objects.filter(uploadUser__businessType=key).order_by('-lastChangeTime')
        currentType = BusinessType.objects.get(id=key).category
    else:
        goodslists = Goods.objects.all().order_by('-lastChangeTime')
    goodslists = goodslists.values('id', 'goodsTitle', 'goodsPrice', 'goodsSrc', 'description')
    businesstype = BusinessType.objects.all()
    businesstype = businesstype.values('category', 'id')
    return render(request, 'homeGoods.html', locals())


def commodity(request):
    key = request.GET.get('goodsid')
    print(key)
    if key:
        goodslists = Goods.objects.get(id=key)
    else:
        goodslists = Goods.objects.all().order_by('-lastChangeTime').first()
    businesstype = BusinessType.objects.all()
    businesstype = businesstype.values('category', 'id')
    currentComments = Comments.objects.filter(goods=goodslists)
    currentComments = currentComments.values('id', 'user__username', 'user__imgSrc', 'created', 'body')
    return render(request, 'homeGoodInfo.html', locals())
